#import "CTLoginVC.h"
#import "M80AttributedLabel.h"
#import "CTHomeVC.h"
#import "CTPrivacyVC.h"
#import "CTVerifyCodeVC.h"
#import "CTEnterPwdVC.h"
#import "THTipInputView.h"
#import "CTInfoVC.h"
#import "CTEncryptTool.h"
#import "CTSetPwdVC.h"
@interface CTLoginVC () <M80AttributedLabelDelegate>
@property (nonatomic ,strong) UIImageView *bgimageV;
@property (nonatomic ,strong) UIButton *welcomButton;
@property (nonatomic ,strong) UIButton *loginButton;  
@property (nonatomic ,strong) UIButton *protocolButton;
@property (nonatomic ,strong) M80AttributedLabel *protocolLabel;
@property (nonatomic ,strong) UIButton *serviceButton;
@property (nonatomic ,strong) CTTFModel *tfModel;
@end
@implementation CTLoginVC
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    NSDictionary *data = @{
        @"navigationRoute" : NSStringFromClass(self.class),
        @"pageIdentity" : kpage_login,
        @"elementUniqueIdentifier"  : kpage_login,
        @"referenceIdentification" : @"",
    };
    [CTUploadManager ct_uploadType:CTUploadTypePage data:data];
}
- (void)setUI {
    self.view.backgroundColor = [UIColor colorFFF];
    self.var_hiddenNavigationBar = YES;
    [self.view addSubview:self.bgimageV];
    [self.view addSubview:self.welcomButton];
    [self.view addSubview:self.phoneView];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.protocolButton];
    [self.view addSubview:self.protocolLabel];
    BOOL showOnlineService = [[NSUserDefaults standardUserDefaults] boolForKey:kShowOnlineService];
    if (showOnlineService) {
        [self.view addSubview:self.serviceButton];
    }
    [self.protocolButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.loginButton.mas_bottom).offset(Ratio(16));
        make.left.mas_equalTo(self.view).offset(Ratio(24));
        make.width.height.mas_equalTo(Ratio(20));
    }];
    [self.protocolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.protocolButton.mas_top).offset(Ratio(2));
        make.left.mas_equalTo(self.protocolButton.mas_right).offset(Ratio(6));
        make.right.mas_lessThanOrEqualTo(self.view).offset(Ratio(-26));
        make.height.mas_equalTo(Ratio(62));
    }];
    @weakify(self);
    [[self.phoneView.contentTF rac_signalForControlEvents:UIControlEventEditingChanged] subscribeNext:^(id x) {
        @strongify(self);
        [self loginObserve];
    }];
}
- (void)loginObserve {
    if (self.phoneView.contentTF.text.length > 11) {
        self.phoneView.contentTF.text = [self.phoneView.contentTF.text substringWithRange:NSMakeRange(0, 11)];
    }
    BOOL canLogin = self.phoneView.contentTF.text.length <= 11;
    self.phoneView.clearBtn.hidden = self.phoneView.contentTF.text.length>0?NO:YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
- (UIImageView *)bgimageV {
    if (!_bgimageV) {
        _bgimageV = [[UIImageView alloc] init];
        _bgimageV.image = [UIImage imageNamed:@"login_bg"];
        _bgimageV.frame = CGRectMake(0, 0, kScreenWidth, Ratio(279));
    }
    return _bgimageV;
}
- (UIButton *)welcomButton
{
    if (!_welcomButton) {
        _welcomButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _welcomButton.frame = CGRectMake(Ratio(30), self.bgimageV.ct_bottom+Ratio(4), Ratio(240), Ratio(44));
        _welcomButton.titleLabel.font = kBoldFontSize(20);
        [_welcomButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_welcomButton setTitle:@"   Welcome to Fazal" forState:UIControlStateNormal];
        [_welcomButton setImage:[UIImage imageNamed:@"login_welcom"] forState:(UIControlStateNormal)];
        _welcomButton.contentMode = UIViewContentModeLeft;
    }
    return _welcomButton;
}
- (CTInputView *)phoneView {
    if (!_phoneView) {
        _phoneView = [[CTInputView alloc] initWithShowLeftView:YES];
        _phoneView.frame = CGRectMake(Ratio(24), self.welcomButton.ct_bottom+Ratio(40), kScreenWidth-Ratio(48), Ratio(46));
        __weak typeof(self) weakSelf = self;
        _phoneView.editDidEndBlock = ^(CTInputView * _Nonnull cell, CTTFModel * _Nonnull tfModel) {
            tfModel.navigationRoute = NSStringFromClass(weakSelf.class);
            tfModel.pageIdentity = ktf_login_phoneNumber;
            tfModel.elementUniqueIdentifier = ktf_login_phoneNumber;
            weakSelf.tfModel = tfModel;
            NSDictionary *data = [weakSelf.tfModel model_keyValues];
            [CTUploadManager ct_uploadType:CTUploadTypeTF data:data];
        };
    }
    return _phoneView;
}
- (UIButton *)loginButton
{
    if (!_loginButton) {
        _loginButton = [[UIButton alloc] init];
        _loginButton.frame = CGRectMake(Ratio(24), self.phoneView.ct_bottom+Ratio(40), kScreenWidth-Ratio(48), Ratio(50));
        [_loginButton setBackgroundColor:[UIColor colorFF6C2E]];
        [_loginButton setTitleColor: [UIColor whiteColor] forState:UIControlStateNormal];
        _loginButton.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:Ratio(15)];
        [_loginButton setTitle:@"Registered/Log in" forState:UIControlStateNormal];
        _loginButton.layer.cornerRadius = Ratio(25);
        _loginButton.layer.masksToBounds = YES;
        [_loginButton addTarget:self action:@selector(loginButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}
- (void)loginButtonClick {
    if(![self.phoneView.contentTF.text isValidPhoneNumber]) {
        [self.view showText:@"Please enter the correct phone number"];
        return ;
    }
    if (!self.protocolButton.selected) {
        __weak typeof(self) weakself = self;
        TJAlertView *aAlertView = [TJAlertView alertWithTitle:@"" subTitle:@"Thank you for using productName. Before using productName, please read Privacy Policy and Loan Terms to understand how we collect, use and store your data to understand the responsibilities and obligations of each party, and other detailed information.If you agree, you can turn on our service. If you choose to decline, we will not be able to serve you." clickTitle:@"Privacy Policy" clickSecond:@"Loan Terms" click:^(NSString * _Nonnull title) {
            NSString *url = @"";
            if ([title isEqualToString:@"Privacy Policy"]) {
                url = [NSURL fullUrlStringForWeb:[CTEnvironmentManager shareManager].privacyPolicyUrl];
            } else {
                url = [NSURL fullUrlStringForWeb:[CTEnvironmentManager shareManager].userAgreementUrl];
            }
            CTPrivacyVC *webVc = [[CTPrivacyVC alloc] initWithTitle:@"" gotoUrl:url];
            [webVc showLeftSingleBack];
            [self.navigationController pushViewController:webVc animated:YES];
        }];
        TJAlertViewAction *aCancelAction = [TJAlertViewAction actionWithTitle:@"Refused" titleColor:[UIColor color161616] backGroudColor:[UIColor whiteColor] handler:nil];
        TJAlertViewAction *aSureAction = [TJAlertViewAction actionWithTitle:@"I have read and accept" titleColor:[UIColor colorFF6C2E] backGroudColor:[UIColor whiteColor] handler:^(TJAlertViewAction *action) {
            weakself.protocolButton.selected = !weakself.protocolButton.selected;
            [weakself requestGalaxyMap];
        }];
        [aAlertView doAddAction:aCancelAction];
        [aAlertView doAddAction:aSureAction];
        [aAlertView doShowAlertView];
        return;
    }
    [self requestGalaxyMap];
}
#pragma mark - check register
- (void)requestGalaxyMap {
    [self.view showLoading];
    NSString *mobile = [CTEncryptTool encryptInfo:returnBeNil(self.phoneView.contentTF.text)];
    [CTService checkIsRegistedWithMobile:returnBeNil(mobile) zuid:[CTUserManager ct_getZuid] backMobile:returnBeNil(self.phoneView.contentTF.text) block:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        if (!isSuccess) {
            [self.view showInfoText:(NSString *)responseObject];
        } else {
            CTUserModel *model = [CTUserModel modelWithDictionary:responseObject[@"matterContent"]];
            CTUserModel *localModel = [CTUserManager shareManager].userModel;
            localModel.wirelessDeviceNumber = self.phoneView.contentTF.text;
            localModel.registeredStatus = model.registeredStatus;
            localModel.hasPassword = model.hasPassword;
            localModel.cipherToken = model.cipherToken;
            localModel.ongoingBusinessArgument = model.ongoingBusinessArgument;
            [[CTUserManager shareManager] updateUserInfo:localModel];
            if (model.registeredStatus) {
                CTEnterPwdVC *enterPwdVC = [[CTEnterPwdVC alloc] init];
                enterPwdVC.codeToken = model.cipherToken;
                enterPwdVC.logoutStatus = model.logOutState;
                [self.navigationController pushViewController:enterPwdVC animated:YES];
            } else {
                CTVerifyCodeVC *verifyVC = [[CTVerifyCodeVC alloc] init];
                verifyVC.codeToken = model.cipherToken;
                verifyVC.operationType = CTOperationTypeRegister;
                [self.navigationController pushViewController:verifyVC animated:YES];
            }
        }
    }];
}
- (UIButton *)protocolButton
{
    if (_protocolButton == nil) {
        _protocolButton = [[UIButton alloc] init];
        [_protocolButton setImage:[UIImage imageNamed:@"login_unsel"] forState:UIControlStateNormal];
        [_protocolButton setImage:[UIImage imageNamed:@"login_sel"] forState:UIControlStateSelected];
        @weakify(self);
        [[_protocolButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            self.protocolButton.selected = !self.protocolButton.selected;
        }];
    }
    return _protocolButton;
}
- (M80AttributedLabel *)protocolLabel
{
    if (_protocolLabel == nil) {
        NSString *privacyString = @"I have read and accept Privacy Policy and  Loan Terms.";
        _protocolLabel = [[M80AttributedLabel alloc]initWithFrame:CGRectZero];
        _protocolLabel.textColor = [UIColor blackColor];
        _protocolLabel.linkColor = [UIColor colorFF6C2E];
        _protocolLabel.backgroundColor = [UIColor clearColor];
        _protocolLabel.highlightColor = [UIColor clearColor];
        _protocolLabel.font = [UIFont systemFontOfSize:13];
        _protocolLabel.underLineForLink = NO;
        _protocolLabel.contentMode = UIViewContentModeLeft;
        _protocolLabel.textAlignment = kCTTextAlignmentLeft;
        _protocolLabel.numberOfLines = 0;
        _protocolLabel.text = privacyString;
        NSRange range1  = [privacyString rangeOfString:@"Privacy Policy"];
        [_protocolLabel addCustomLink:[NSValue valueWithRange:range1] forRange:range1];
        NSRange range2  = [privacyString rangeOfString:@"Loan Terms"];
        [_protocolLabel addCustomLink:[NSValue valueWithRange:range2] forRange:range2];
        _protocolLabel.delegate = self;
    }
    return _protocolLabel;
}
#pragma mark - M80label delegate
- (void)m80AttributedLabel:(M80AttributedLabel *)label clickedOnLink:(id)linkData
{
    NSString *rangeStr =[NSString stringWithFormat:@"%@",linkData];
    NSString *url = @"";
    NSString *title = @"";
    if ([rangeStr containsString:@"14"]){
        url = [NSURL fullUrlStringForWeb:[CTEnvironmentManager shareManager].privacyPolicyUrl];
    }else if ([rangeStr containsString:@"10"]){
        url = [NSURL fullUrlStringForWeb:[CTEnvironmentManager shareManager].userAgreementUrl];
    }
    CTPrivacyVC *webVc = [[CTPrivacyVC alloc] initWithTitle:title gotoUrl:url];
    [webVc showLeftSingleBack];
    [self.navigationController pushViewController:webVc animated:YES];
}
- (UIButton *)serviceButton
{
    if (!_serviceButton) {
        _serviceButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _serviceButton.frame = CGRectMake(0, kScreenHeight-[UIDevice ct_safeBottom]-Ratio(40), kScreenWidth, Ratio(20));
        _serviceButton.titleLabel.font = kBoldFontSize(13);
        [_serviceButton setTitleColor:[UIColor colorFF6C2E] forState:UIControlStateNormal];
        [_serviceButton setTitle:@"  Online services" forState:UIControlStateNormal];
        [_serviceButton setImage:[UIImage imageNamed:@"customer_service"] forState:(UIControlStateNormal)];
        _serviceButton.contentMode = UIViewContentModeLeft;
        [_serviceButton addTarget:self action:@selector(onlineService) forControlEvents:UIControlEventTouchUpInside];
    }
    return _serviceButton;
}
- (void)onlineService {
    NSDictionary *data = @{
        @"navigationRoute" : NSStringFromClass(self.class),
        @"pageIdentity" : kbtn_login_service,
        @"elementUniqueIdentifier"  : kbtn_login_service,
    };
    [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
    NSString *fullUrl = [NSURL fullUrlStringForWeb:@"#/onlineservice"];
    CTHomeVC *webVc = [[CTHomeVC alloc] initWithTitle:@"Online services" gotoUrl:fullUrl];
    [webVc showLeftSingleBack];
    [self.navigationController pushViewController:webVc animated:YES];
}
@end
